package main

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func GetCurrentPath() (string, error) {
	//获取当前执行文件路径
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	//获取文件的绝对路径
	path, err := filepath.Abs(file)
	if err != nil {
		return "", err
	}
	i := strings.LastIndex(path, "/")
	if i < 0 {
		i = strings.LastIndex(path, "\\")
	}
	if i < 0 {
		return "", errors.New(`error: Can't find "/" or "\".`)
	}
	return string(path[0 : i+1]), nil
}

func server(writer http.ResponseWriter, request *http.Request) {
	path, e := GetCurrentPath()
	if e != nil {
		panic(e)
	}

	file, err := os.Open(path + "config")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	all, err := ioutil.ReadAll(file)
	if err != nil {
		panic(err)
	}

	writer.Header().Set("Content-Type", "application/json;charset=UTF-8")
	write, err := writer.Write(all)
	if err != nil {
		panic(err)
	}

	fmt.Println(write)
}

func main() {
	http.HandleFunc("/api/config/list/", server)
	//http.ListenAndServe(":8888",nil)

	//启用https的监听
	//http.ListenAndServeTLS(":8888", "server.crt", "server.key", nil)
	http.ListenAndServe(":8888", nil)
}
